package wh.coach._thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author xhw
 * @Date 2023/10/22
 * @Version 1.0
 */
public class IntIncrease {
    static int num = 0;
    //添加一个可重入锁
    static Lock lock = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {
        Thread[] threads = new Thread[100];

        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 0; j < 10000; j++) {
                    increase();
                }
            });
        }

        for (Thread thread : threads) {
            thread.start();
        }

        for (Thread thread : threads) {
            thread.join();
        }

        System.out.println(num);
    }

    private static void increase() {
        //加锁
        try {

            lock.lock();
            num++;

        } finally {
            //释放锁
            lock.unlock();
        }

    }
}
